package com.fenghongzhang.day012;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import java.util.regex.Pattern;


/**
 * A simple {@link Fragment} subclass.
 */
public class RegisterFragment extends Fragment {
    private EditText regName;
    private EditText regPwd;


    private MainActivity mainActivity;

    private Button register;
    public RegisterFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mainActivity = (MainActivity) getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View inflate = inflater.inflate(R.layout.fragment_register, container, false);
        regName = (EditText) inflate.findViewById(R.id.reg_name);
        regPwd = (EditText) inflate.findViewById(R.id.reg_pwd);
        register = (Button) inflate.findViewById(R.id.register);

        /**
         * 用户在注册Fragment输入用户名和密码（用户名和密码必须是英文且长度大于6），
         */

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = regName.getText().toString();
                String pwd = regPwd.getText().toString();

                String reg = "^[A-Za-z]{6,}$";
//                boolean matches = Pattern.matches(reg, name);
//                boolean matches1 = Pattern.matches(reg, pwd);

                if(Pattern.matches(reg,name) && Pattern.matches(reg, pwd)){

                    //点击注册按钮，验证成功后，将用户名和密码存储到SP中，且跳转到登录Fragment页面。
                    SharedPreferences sp = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString("name",name);
                    edit.putString("pwd",pwd);

                    //多加一个值,用来判断是否注册过
                    edit.putBoolean("isRegister",true);
                    edit.commit();

                    //跳
                    mainActivity.setPage(0);

                }

            }
        });


        return inflate;
    }
}
